//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends egret.DisplayObjectContainer {



    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event: egret.Event) {

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin

            context.onUpdate = () => {

            }
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        this.runGame().catch(e => {
            console.log(e);
        })



    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        const result = await RES.getResAsync("description_json")
        this.startAnimation(result);
        await platform.login();
        const userInfo = await platform.getUserInfo();
        console.log(userInfo);

    }

    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await RES.loadConfig("resource/default.res.json", "resource/");
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private textfield: egret.TextField;

    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene() {
        
        let sky = this.createBitmapByName("newbg_jpg");
        this.addChild(sky);
        
        let stageW = this.stage.stageWidth;
        let stageH = this.stage.stageHeight;

        sky.width = stageW;
        sky.height = stageH;

        /***************头像***************/
        // 定义一个bitmap
        let portrait = new egret.Bitmap();
        // 加载图片纹理
        portrait.texture = RES.getRes('ygz_jpg');
        // portrait.fillMode = egret.BitmapFillMode.CLIP;
        // 添加到显示列表
        // this.addChild(portrait);

        // 设置头像的宽高
        portrait.width = stageW * 0.5;
        portrait.height = stageH * 0.5;

        // 设置锚点的方式来实现水平居中
        portrait.anchorOffsetX = portrait.width * 0.5;
        portrait.anchorOffsetY = portrait.height * 0.5;

        portrait.x = stageW * 0.5;
        portrait.y = portrait.height * 0.5;

        // 如果它的锚点是在原点0,0的位置，设置水平居中
        // portrait.x = stageW * 0.5 - portrait.width * 0.5;

        // 设置遮罩
        var circle: egret.Shape = new egret.Shape();
        // 绘制一个圆
        circle.graphics.beginFill(0xff0000);
        circle.graphics.drawCircle(stageW*0.5, portrait.height*0.5, portrait.width*0.5);
        circle.graphics.endFill();
        // this.addChild(circle);

        // 设置圆形遮罩，让头像变成圆形图片
        portrait.mask = circle;

        /***************歌词/诗文***************/
        // 定义一个文本
        var text: egret.TextField = new egret.TextField();
        // 直接添加到显示列表中
        // this.addChild(text);
        // 设置内容
        text.text = `
《乡愁》 
余光中

小时候，

乡愁是一枚小小的邮票，

我在这头，

母亲在那头。


长大后，

乡愁是一张窄窄的船票，

我在这头，

新娘在那头。


后来啊，

乡愁是一方矮矮的坟墓，

我在外头，

母亲在里头。


而现在，

乡愁是一湾浅浅的海峡，

我在这头，

大陆在那头。

        `;
        // 设置文本的宽度是屏幕的宽度
        text.width = stageW;
        // 设置文本的背景色
        text.background = true;
        text.backgroundColor = 0xe8fff5;

        // 设置文本的位置，距离头像底部10
        text.y = portrait.height + 10;
        // 设置字体颜色
        text.textColor = 0x199fc2;
        // 设置文本的高度（文本内容上下留10）
        text.height = text.height + 20;
        // 设置文本居中（水平、垂直）
        text.textAlign = egret.HorizontalAlign.CENTER;
        text.verticalAlign = egret.VerticalAlign.MIDDLE;

        /***************滚动视图***************/
        // 定义一个滚动视图
        var scroll: egret.ScrollView = new egret.ScrollView();
        // 添加到显示列表中去
        this.addChild(scroll);
        // 设置可滚动范围
        scroll.width = stageW;
        scroll.height = stageH;

        // 定义一个容器
        var content: egret.Sprite = new egret.Sprite();
        // 设置容器可以滚动
        scroll.setContent(content);
        // 添加头像和文本到容器中
        content.addChild(portrait);
        content.addChild(circle);
        content.addChild(text);

        /***************让头像滚动起来****************/
        var change = () => {
            // 默认portrait的旋转角度为0
            portrait.rotation = 0;
            // 使用Tween动画库来激活portrait
            egret.Tween.get(portrait).to({
                rotation: 360
            }, 5000).call(change, this);
        }

        // 调用change函数
        change();
        
        /****************设置背景音乐*******************/
        var player = RES.getRes("xhgt_mp3");
        player.play();

    }

    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string) {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }

    /**
     * 描述文件加载成功，开始播放动画
     * Description file loading is successful, start to play the animation
     */
    private startAnimation(result: string[]) {
        let parser = new egret.HtmlTextParser();

        let textflowArr = result.map(text => parser.parse(text));
        let textfield = this.textfield;
        let count = -1;
        let change = () => {
            count++;
            if (count >= textflowArr.length) {
                count = 0;
            }
            let textFlow = textflowArr[count];

            // 切换描述内容
            // Switch to described content
            textfield.textFlow = textFlow;
            let tw = egret.Tween.get(textfield);
            tw.to({ "alpha": 1 }, 200);
            tw.wait(2000);
            tw.to({ "alpha": 0 }, 200);
            tw.call(change, this);
        };

        change();
    }
}